<template>
  <a-card>
    <a-form layout="horizontal" :form="searchForm" @submit="handleSearch" autocomplete="off">
      <a-row type="flex" justify="start" :gutter="15">
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-auto-complete :data-source="suppliers" v-decorator="['supplier']" :placeholder="$t('supplier')" :filter-option="filterOption" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-input v-decorator="['supplierHotelId']" :placeholder="$t('supplier_hotel_id')" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select v-decorator="['isMapping',{ initialValue: '' }]">
              <a-select-option value="">
                {{$t('is_mapping')}}
              </a-select-option>
              <a-select-option value="True">
                {{$t('yes')}}
              </a-select-option>
              <a-select-option value="False">
                {{$t('no')}}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-input v-decorator="['hotelId']" :placeholder="$t('hotel_id')" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select v-decorator="['isTop',{ initialValue: '' }]">
              <a-select-option value="">
                {{$t('sale_top')}}
              </a-select-option>
              <a-select-option value="True">
                {{$t('yes')}}
              </a-select-option>
              <a-select-option value="False">
                {{$t('no')}}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select v-decorator="['isAvail',{ initialValue: '' }]">
              <a-select-option value="">
                {{$t('available')}}
              </a-select-option>
              <a-select-option value="True">
                {{$t('yes')}}
              </a-select-option>
              <a-select-option value="False">
                {{$t('no')}}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :md="3" :sm="24">
          <a-form-item>
            <a-select v-decorator="['hotelStar',{ initialValue: '' }]">
              <a-select-option value="">
                {{ $t('hotel_star') }}
              </a-select-option>
              <a-select-option value="0">0 {{ $t('star') }}</a-select-option>
              <a-select-option value="1">1 {{ $t('star') }}</a-select-option>
              <a-select-option value="2">2 {{ $t('star') }}</a-select-option>
              <a-select-option value="3">3 {{ $t('star') }}</a-select-option>
              <a-select-option value="4">4 {{ $t('star') }}</a-select-option>
              <a-select-option value="5">5 {{ $t('star') }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row type="flex" justify="start" :gutter="15">
        <a-col :md="4" :sm="24">
          <a-form-item>
            <a-auto-complete :data-source="countryList" v-decorator="['countryName']" :placeholder="$t('country')" :allowClear="true" :filter-option="filterOption"/>
          </a-form-item>
        </a-col>
        <a-col :md="4" :sm="24">
          <a-form-item>
            <a-input v-decorator="['cityName']" :placeholder="$t('city')" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="6" :sm="24">
          <a-form-item>
            <a-input v-decorator="['hotelName']" :placeholder="$t('hotel_name')" :allowClear="true"/>
          </a-form-item>
        </a-col>
        <a-col :md="10" :sm="24">
          <a-form-item>
          <a-space>
            <a-button htmlType="submit" type="primary" icon="search">{{ $t('search') }}</a-button>
            <a-button @click="handleReset">
              {{ $t("reset") }}
            </a-button>
          </a-space>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <a-table size="middle" :columns="columns" :data-source="data" :pagination="{ showSizeChanger: true, showQuickJumper: true, size:'middle', showTotal:(total, range) => `${range[0]}-${range[1]} / ${total}`, current: pageIndex, pageSize: pageSize, total: total, pageSizeOptions:['10','20','30','50','100','1000','2000'], }" :row-key="record => record.id" :loading="loading" @change="handleTableChange" :scroll="{ x: 'max-content' }">
      <template slot="supplier" slot-scope="text, record">
        <span class="v1">{{text}}</span>
        <span class="v2"><a @click="showMapForm(record)">{{$t("hotel")}}</a></span>
      </template>
      <template slot="supplierHotelId" slot-scope="text, record">
        <span class="v1">{{text}}</span>
        <span class="v2">{{record.hotelId}}</span>
      </template>
      <template slot="hotelNameEn" slot-scope="text, record">
        <span class="v1"><a @click="openSupplierHotel(record.supplier,record.supplierHotelId)">{{ record.supplierHotelNameEn }} {{ record.supplierHotelNameCn }}</a></span>
        <span class="v2"><a @click="openHotel(record.hotelId)" v-if="record.hotelId > 0">{{ record.hotelNameEn }} {{ record.hotelNameCn }}</a></span>
      </template>
      <template slot="countryName" slot-scope="text, record">
        <span class="v1">{{record.supplierCountryName}}</span>
        <span class="v2">{{text}}</span>
      </template>
      <template slot="cityName" slot-scope="text, record">
        <span class="v1">{{record.supplierCityName}}</span>
        <span class="v2">{{text}}</span>
      </template>
      <template slot="hotelAddressEn" slot-scope="text, record">
        <span class="v1">{{record.supplierHotelAddressEn}}</span>
        <span class="v2">{{text}}</span>
      </template>
      <template slot="hotelTel" slot-scope="text, record">
        <span class="v1">{{record.supplierHotelTel}}</span>
        <span class="v2">{{text}}</span>
      </template>
      <template v-for="(item, index) in columns" :slot="item.slotName">
        <span :key="index">{{ $t(item.slotName) }}</span>
      </template>
    </a-table>

    <a-modal v-model="mapFormVisible" :maskClosable="false" :title="$t('map_hotel')" width="90%">
      <a-table size="small" :columns="hotelColumns" :data-source="hotelData" :row-key="record => record.hotelId" :loading="hotelLoading"  :pagination="{ showSizeChanger: true, showQuickJumper: true, size:'small', showTotal:(total, range) => `${range[0]}-${range[1]} / ${hotelTotal}`, current: hotelPageIndex, pageSize: hotelPageSize, total: hotelTotal, pageSizeOptions:['5','10','20','30','50','100','1000','2000'],}" @change="handleHotelTableChange" :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange, type: 'radio', getCheckboxProps: getCheckboxProps }" :scroll="{ x: 'max-content' }">
        <template slot="title">
          <a-form-model :model="searchHotelParams" layout="inline" @submit="handleHotelSearch" autocomplete="off">
            <a-form-model-item>
              <a-input v-model="searchHotelParams.hotelId" :placeholder="$t('hotel_id')" :allowClear="true" />
            </a-form-model-item>
            <a-form-model-item>
              <a-auto-complete v-model="searchHotelParams.countryName" :data-source="countryList" :placeholder="$t('country')" :allowClear="true" :filter-option="filterOption"/>
            </a-form-model-item>
            <a-form-model-item>
              <a-input v-model="searchHotelParams.cityName" :placeholder="$t('city')" :allowClear="true"/>
            </a-form-model-item>
            <a-form-model-item>
              <a-input v-model="searchHotelParams.hotelName" :placeholder="$t('hotel_name')" :allowClear="true" style="width: 300px"/>
            </a-form-model-item>
            <a-form-model-item>
              <a-button htmlType="submit" type="primary" icon="search">{{ $t('search') }}</a-button>
            </a-form-model-item>
            <a-form-model-item>
              <a-button @click="handleHotelReset">
                {{ $t("reset") }}
              </a-button>
            </a-form-model-item>
          </a-form-model>
        </template>
        <template slot="hotelId" slot-scope="text, record">
          <span class="v1" :title="supplierHotel.supplier">{{ supplierHotel.supplierHotelId }}</span>
          <span class="v2">{{record.hotelId}}</span>
        </template>
        <template slot="hotelNameEn" slot-scope="text, record">
          <span class="v1">{{ supplierHotel.supplierHotelNameEn }} {{ supplierHotel.supplierHotelNameCn }}</span>
          <span class="v2">{{ record.hotelNameEn }} {{ record.hotelNameCn }}</span>
        </template>
        <template slot="countryName" slot-scope="text, record">
          <span class="v1">{{supplierHotel.supplierCountryName}}</span>
          <span class="v2">{{record.countryName}}</span>
        </template>
        <template slot="cityName" slot-scope="text, record">
          <span class="v1">{{supplierHotel.supplierCityName}}</span>
          <span class="v2">{{record.cityName}}</span>
        </template>
        <template slot="hotelAddressEn" slot-scope="text, record">
          <span class="v1">{{supplierHotel.supplierHotelAddressEn}}</span>
          <span class="v2">{{record.hotelAddressEn}}</span>
        </template>
        <template slot="hotelTel" slot-scope="text, record">
          <span class="v1">{{supplierHotel.supplierHotelTel}}</span>
          <span class="v2">{{record.hotelTel}}</span>
        </template>
        <template v-for="(item, index) in hotelColumns" :slot="item.slotName">
          <span :key="index">{{ $t(item.slotName) }}</span>
        </template>
      </a-table>

      <template slot="footer">
        <a-space>
          <a-popconfirm :title='$t("are_you_sure")' ok-text="Yes" okType="danger" cancel-text="No" :disabled="!(this.selectedRows.length == 1)" @confirm="saveMapping">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-button type="primary" :loading="saveLoading" :disabled="!(this.selectedRows.length == 1)">
              {{ $t("save") }}{{ $t("mapping") }}
            </a-button>
          </a-popconfirm>
          <a-popconfirm :title='$t("are_you_sure")' ok-text="Yes" okType="danger" cancel-text="No" :disabled="!(this.supplierHotel.hotelId > 0)" @confirm="cancelMapping">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-button type="primary" :loading="cancelLoading" :disabled="!(this.supplierHotel.hotelId > 0)">
              {{ $t("cancel") }}{{ $t("mapping") }}
            </a-button>
          </a-popconfirm>
          <a-popconfirm :title='$t("are_you_sure")' ok-text="Yes" okType="danger" cancel-text="No" :disabled="this.supplierHotel.hotelId > 0" @confirm="newHotel">
            <a-icon slot="icon" type="question-circle-o" style="color: red" />
            <a-button type="primary" :loading="newLoading" :disabled="this.supplierHotel.hotelId > 0">
              {{ $t("new_hotel") }}
            </a-button>
          </a-popconfirm>
        </a-space>
      </template>
    </a-modal>
  </a-card>
</template>

<script>
import {getPublicData} from '@/services/public'
import {getMappingPageList,saveMapping,addNewHotel,cancelMapping} from '@/services/mapping'
import {getHotelList} from '@/services/hotel'

export default {
  name: "HotelMapping",
  i18n: require('../i18n'),
  data() {
    return {
      suppliers: [],
      countryList: [],
      searchParams: {},
      searchForm: this.$form.createForm(this, {name: 'search'}),
      pageIndex: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      data: [],
      columns: [
        {
          dataIndex: 'supplier',
          align: 'center',
          slotName: "supplier",
          slots: { title: 'supplier' },
          scopedSlots: { customRender: 'supplier' },
        },
        {
          dataIndex: 'supplierHotelId',
          align: 'center',
          slotName: "hotel_id1",
          slots: { title: 'hotel_id1' },
          scopedSlots: { customRender: 'supplierHotelId' },
        },
        {
          dataIndex: 'hotelNameEn',
          align: 'left',
          slotName: "hotel_name",
          slots: { title: 'hotel_name' },
          scopedSlots: { customRender: 'hotelNameEn' },
          ellipsis: true,
        },
        {
          dataIndex: 'countryName',
          align: 'left',
          slotName: "country",
          slots: { title: 'country' },
          scopedSlots: { customRender: 'countryName' },
        },
        {
          dataIndex: 'cityName',
          align: 'left',
          slotName: "city",
          slots: { title: 'city' },
          scopedSlots: { customRender: 'cityName' },
        },
        {
          dataIndex: 'hotelAddressEn',
          align: 'left',
          slotName: "address",
          slots: { title: 'address' },
          scopedSlots: { customRender: 'hotelAddressEn' },
          ellipsis: true,
        },
        {
          dataIndex: 'hotelTel',
          align: 'left',
          slotName: "tel",
          slots: { title: 'tel' },
          scopedSlots: { customRender: 'hotelTel' },
        },{
          dataIndex: 'updatedByName',
          align:'center',
          slotName: "updatedByName",
          slots: { title: 'updatedByName' },
        },{
          dataIndex: 'updatedTime',
          align:'center',
          slotName: "updatedTime",
          slots: { title: 'updatedTime' },
        },
      ],
      hotelLoading: false,
      mapFormVisible: false,
      hotelPageIndex: 1,
      hotelPageSize: 5,
      hotelTotal: 0,
      supplierHotel: {},
      hotelData:[],
      hotelColumns: [
        {
          dataIndex: 'hotelId',
          align: 'center',
          slotName: "hotel_id1",
          slots: { title: 'hotel_id1' },
          scopedSlots: { customRender: 'hotelId' },
        },
        {
          dataIndex: 'hotelNameEn',
          align: 'left',
          slotName: "hotel_name",
          slots: {title: 'hotel_name'},
          scopedSlots: {customRender: 'hotelNameEn'},
          ellipsis: true,
        },
        {
          dataIndex: 'countryName',
          align: 'left',
          slotName: "country",
          slots: { title: 'country' },
          scopedSlots: {customRender: 'countryName'},
        },
        {
          dataIndex: 'cityName',
          align: 'left',
          slotName: "city",
          slots: { title: 'city' },
          scopedSlots: {customRender: 'cityName'},
        },
        {
          dataIndex: 'hotelAddressEn',
          align: 'left',
          slotName: "address",
          slots: { title: 'address' },
          scopedSlots: { customRender: 'hotelAddressEn' },
          ellipsis: true,
        },
        {
          dataIndex: 'hotelTel',
          align: 'left',
          slotName: "tel",
          slots: { title: 'tel' },
          scopedSlots: { customRender: 'hotelTel' },
        },
      ],
      selectedRows: [],
      selectedRowKeys: [],
      searchHotelParams: {},
      saveLoading: false,
      cancelLoading: false,
      newLoading: false,
    }
  },
  methods: {
    getData() {
      getPublicData('sup_dis_coun').then(res => {
        const {suppliers, countryList} = res.data
        this.suppliers = suppliers
        countryList.forEach(item => {
          this.countryList.push({label: item.countryNameEn, value: item.countryNameEn, text: item.countryNameEn})
        })
      }).catch(error => {
        console.log(error)
      })
    },
    fetchData(){
      this.loading = true
      getMappingPageList(this.pageIndex, this.pageSize, this.searchParams).then(res => {
        const {rows, total} = res.data.data
        this.data = rows
        this.total = total
        this.loading = false
      }).catch(error => {
        console.log(error)
        this.loading = false
      })
    },
    handleTableChange(pagination) {
      if (this.pageIndex === pagination.current && this.pageSize === pagination.pageSize)
        return

      this.pageIndex = pagination.current;
      this.pageSize = pagination.pageSize;
      this.fetchData()
    },
    handleSearch(e) {
      e.preventDefault();
      this.searchForm.validateFields((error, values) => {
        this.searchParams = values;
      });
      this.pageIndex = 1
      this.fetchData()
    },
    handleReset() {
      this.searchForm.resetFields();
    },
    openSupplierHotel(supplier, supplierHotelId){
      this.$openPage('/supplier/hotel/' + supplier + '/' + supplierHotelId, "[" + supplier + "][" + supplierHotelId + "]")
    },
    openHotel(hotelId){
      this.$openPage('/hotel/detail/' + hotelId, "[" + hotelId + "]")
    },
    filterOption(input, option) {
      return (
          option.componentOptions.children[0].text.toUpperCase().indexOf(input.toUpperCase()) >= 0
      );
    },
    showMapForm(record) {
      this.mapFormVisible = true
      this.supplierHotel = record
      this.initHotelData(record, [])
      if (this.supplierHotel.hotelId > 0)
        this.searchHotelParams = {
          hotelId: this.supplierHotel.hotelId,
          countryName: '',
          cityName: '',
          hotelName: '',
        };
      else
        this.searchHotelParams = {
          hotelId: this.supplierHotel.hotelId,
          countryName: this.supplierHotel.supplierCountryName,
          cityName: this.supplierHotel.supplierCityName,
          hotelName: this.supplierHotel.supplierHotelNameEn,
        };
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    getCheckboxProps(record){
      return {
        props: {
          disabled: record.supplier !== '' && record.supplier !== undefined,
        },
      }
    },
    handleHotelSearch(e) {
      e.preventDefault()
      this.hotelPageIndex = 1
      this.searchHotels()
    },
    handleHotelReset() {
      if (this.supplierHotel.hotelId > 0)
        this.searchHotelParams = {
          hotelId: this.supplierHotel.hotelId,
          countryName: '',
          cityName: '',
          hotelName: '',
        };
      else
        this.searchHotelParams = {
          hotelId: this.supplierHotel.hotelId,
          countryName: this.supplierHotel.supplierCountryName,
          cityName: this.supplierHotel.supplierCityName,
          hotelName: this.supplierHotel.supplierHotelNameEn,
        };
    },
    initHotelData(record, rows){
      this.hotelData = rows
      this.selectedRows = []
      this.selectedRowKeys = []
    },
    handleHotelTableChange(pagination) {
      if (this.hotelPageIndex === pagination.current && this.hotelPageSize === pagination.pageSize)
        return

      this.hotelPageIndex = pagination.current;
      this.hotelPageSize = pagination.pageSize;
      this.searchHotels()
    },
    searchHotels(){
      this.hotelLoading = true
      getHotelList(this.hotelPageIndex, this.hotelPageSize, this.searchHotelParams).then(res => {
        this.initHotelData(this.supplierHotel, res.data.data.rows)
        this.hotelTotal = res.data.data.total
        this.hotelLoading = false
      }).catch(error => {
        console.log(error)
        this.hotelLoading = false
      })
    },
    saveMapping(){
      this.saveLoading = true
      saveMapping({
        hotelId: this.selectedRows[0].hotelId,
        supplier: this.supplierHotel.supplier,
        supplierHotelId: this.supplierHotel.supplierHotelId,
      }).then(res => {
        if(res.data.success) {
          this.$message.success(this.$t("submitSuccess"));
          this.fetchData()
          this.mapFormVisible = false
        }else
          this.$message.error(res.data.message);
        this.saveLoading = false
      }).catch(error => {
        console.log(error)
        this.saveLoading = false
      })
    },
    cancelMapping(){
      this.cancelLoading = true
      cancelMapping({
        hotelId: this.supplierHotel.hotelId,
        supplier: this.supplierHotel.supplier,
        supplierHotelId: this.supplierHotel.supplierHotelId,
      }).then(res => {
        if (res.data.success){
          this.$message.success(this.$t("submitSuccess"))
          this.fetchData()
          this.mapFormVisible = false
        }else
            this.$message.error(res.data.message);
        this.cancelLoading = false
      }).catch(error => {
        console.log(error)
        this.cancelLoading = false
      })
    },
    newHotel(){
      this.newLoading = true
      addNewHotel({
        supplier: this.supplierHotel.supplier,
        supplierHotelId: this.supplierHotel.supplierHotelId,
      }).then(res => {
        if(res.data.success) {
          this.$message.success(this.$t("submitSuccess"))
          this.fetchData()
          this.mapFormVisible = false
        }else
          this.$message.error(res.data.message);
        this.newLoading = false
      }).catch(error => {
        console.log(error)
        this.newLoading = false
      })
    },
  },
  created() {
    this.getData();
  },
}
</script>

<style scoped>
.v1 {
  border-bottom: 1px solid rgb(136, 136, 136);
  width: 100%;
  display: block;
}
.v2 {
  width: 100%;
  display: block;
  height: 21px;
}
.ant-table-placeholder{
  padding: 0;
  border-top: none;
}
</style>